package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.entity.Admin;
import cn.kgc.excpetion.GraceException;
import cn.kgc.form.AdminLoginForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.AdminService;
import cn.kgc.utils.JwtUtil;
import cn.kgc.vo.AdminVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.kgc.base.SystemConstant.LOGIN_TYPE_ADMIN;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员认证模块")
@Validated
@Slf4j
@SuppressWarnings("all")
public class AdminController {
    @Resource
    private AdminService adminService;
    @Resource
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public GraceJSONResult login(@RequestBody @Validated AdminLoginForm adminLoginForm){
       Admin admin=
               adminService.adminLogin(adminLoginForm.getUsername(),adminLoginForm.getPassword());
       if(admin==null){
          GraceException.display(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
       }
       return GraceJSONResult.ok(jwtUtil.createToken(admin.getId(), LOGIN_TYPE_ADMIN));
    }

    @PostMapping("/info")
    @ApiOperation(value = "获得管理员信息")
    public GraceJSONResult info(){
        //获得登录的用户的id
        String adminId = JwtInterceptor.adminUserIds.get();
        if(StrUtil.isBlank(adminId)){
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
        }
        //根据id查询用户信息
        Admin admin = adminService.getById(adminId);
        AdminVo adminVo=new AdminVo();
        BeanUtil.copyProperties(admin,adminVo);
        return GraceJSONResult.ok(adminVo);
    }

}
